<template>
  <div class="spu">
    <el-form label-width="80px" :model="spu" ref="form">
      <el-form-item label="SPU名称"><el-input placeholder="SPU名称" v-model="spu.spuName"></el-input ></el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option v-for="item in tradeMarkList" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述"><el-input type="textarea" rows="4" v-model="spu.description"></el-input></el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-success="handleUploadSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttrList.length}项未选`" v-model="attrId">
          <el-option v-for="item in unSelectSaleAttrList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-button icon="el-icon-plus" type="primary" :disabled="!attrId" @click="handleAddAttr">添加销售属性</el-button></el-form-item>
      <el-form-item>
        <el-table border :data="spu.spuSaleAttrList">
          <el-table-column label="序号" width="80" align="center">
            <template v-slot="{$index}">
              {{$index+1}}
            </template>
          </el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template v-slot="{row}">
              <el-tag :key="tag.id" v-for="(tag, index) in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="handleClose(row,index)">{{tag.saleAttrValueName}}</el-tag>
              <!-- @keyup.enter.native="handleInputConfirm" -->
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small"  @blur="handleInputConfirm(row)"></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{$index}">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdate">保存</el-button>
        <el-button @click="handleQuit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSpuById ,getTrademarkList , getSpuImageList, getBaseSaleAttrList, updateOrSaveSpuInfo} from "@/api/product/spu";
export default {
  name: 'SpuForm',
  props:{
    rowId:{
      type:[Number,String],
      default:''
    },
    initSelectionThree:{
      type:Number,
      default:0
    }
  },
  data(){
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu:{
        "category3Id": 0, // 三级分类id
        "tmId": '',// 品牌的id
        "description": "", // spu描述
        "spuName": "", // spu名称
        // "id": 0,
        "spuImageList": [ // 收集SPU图片的信息
          {
            // "id": 0,
            // "imgName": "string",
            // "imgUrl": "string",
            // "spuId": 0
          }
        ],
        "spuSaleAttrList": [ // 平台属性和属性值的收集
          // {
          //   "baseSaleAttrId": 0,
          //   "id": 0,
          //   "saleAttrName": "string",
          //   "spuId": 0,
          //   "spuSaleAttrValueList": [
          //     {
          //       "baseSaleAttrId": 0,
          //       "id": 0,
          //       "isChecked": "string",
          //       "saleAttrName": "string",
          //       "saleAttrValueName": "string",
          //       "spuId": 0
          //     }
          //   ]
          // }
        ]
      }, // 存储spu的信息
      tradeMarkList:[],// 储存品牌信息
      spuImageList:[],// 储存SPU图片的数据
      SaleAttrList:[],// 销售属性的数据 (项目全部的销售属性 只有3个 颜色 版本 尺码)
      attrId:'' // 收集未选择的销售属性的id
    }
  },
  created(){
    this.getData(this.rowId)
  },
  computed:{
    unSelectSaleAttrList(){
      return this.SaleAttrList.filter((item)=>{
        const res = this.spu.spuSaleAttrList.some(item2=>{
          return item2.baseSaleAttrId === item.id
        })
        return !res
      })
    }
  },
  methods:{
    async getData(id){
      // 获取品牌的信息
      const tradeMarkListRes = await getTrademarkList()
      this.tradeMarkList = tradeMarkListRes
      // 获取平台的全部销售属性
      const baseSaleAttrListRes= await getBaseSaleAttrList()
      this.SaleAttrList = baseSaleAttrListRes
      if (this.rowId) {
        // 获取SPU信息
        const spuRes = await getSpuById(id)
        this.spu = spuRes
        // 获取SPU图片接口的列表
        const spuImageListRes= await getSpuImageList(id)
        const _imgList = spuImageListRes
        _imgList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        });
        this.spuImageList = _imgList 
      } 
    },
    // 添加销售属性按钮
    handleAddAttr(){
      const baseSaleAttrId = this.attrId
      const saleAttrName = this.unSelectSaleAttrList.find(item=>item.id===baseSaleAttrId).name
      const _newAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]}
      this.spu.spuSaleAttrList.push(_newAttr)
      // 添加了属性后,清空
      this.attrId = ''
    },
    // 照片上传成功回调
    handleUploadSuccess(response, file, fileList){
      // console.log('response:', response)
      // console.log('file:', file)
      // console.log('fileList:', fileList)

      // 照片回显处理
      this.spuImageList = fileList
      // 关联参数到spu对象
      this.spu.spuImageList = fileList.map(item=>{
        return {
          imgName:item.name,
          imgUrl:(item.response && item.response.data) || item.url
        }
      })
    },
    // 照片删除回调
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      this.spuImageList = fileList
    },
    // 照片预览功能
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    handleQuit(bol){
      this.$emit('changeScene',bol)
    },
    // tag标签删除事件
    handleClose(row,index) {
      row.spuSaleAttrValueList.splice(index,1)
    },
    // 底部表格添加属性值的按钮
    showInput(row) {
      this.$set(row,'inputVisible',true)
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 底部表格input输入框失焦事件
    handleInputConfirm(row) {
        let {inputValue , baseSaleAttrId} = row
        // 属性值不能为空
        if (inputValue.trim() === '') {
          this.$message.error('属性值不能为空')
          return
        }
        // 判断内容是否重复
        const _res = row.spuSaleAttrValueList.some(item=>item.saleAttrValueName === inputValue)
        if (_res) {
          this.$message.error('不能输入重复的属性值')
          inputValue = ''
          return 
        }
        const _obj = {saleAttrValueName:inputValue, baseSaleAttrId}
        // 失焦就添加数据
        row.spuSaleAttrValueList.push(_obj)
        // 切换显示
        row.inputVisible = false
        // 清空内容
        inputValue = ''
    },
    // 表格删除事件
    handleDelete(index){
      this.$confirm('确定要删除吗?','提示',{
        type:'warning',
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      })
      .then(()=>{this.spu.spuSaleAttrList.splice(index,1)})
      .catch(()=>{})
    },
    // 新增或修改SPU 的保存按钮
    async addOrUpdate(){
      // console.log('this.rowId:', this.rowId)
      // console.log('this.spu:', this.spu)
      if (!this.rowId) {
        this.spu.category3Id = this.initSelectionThree
      }
      await updateOrSaveSpuInfo(this.spu)
      this.$message.success(this.rowId?'修改成功':'新增成功')
      this.handleQuit(true)
    }
  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
